<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <!--如果是IE 就以标准渲染-->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <!-- 视窗——————响应式布局 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" />

    <!--当前页面的三要素-->
    <title>运维系统APP</title>
    <meta name="description" content="聚能优电" />
    <meta http-equiv="keywords" content="聚能优电" />
    <script type="text/javascript" src="../../js/verify.js"></script>
    <script type="text/javascript" src="../../js/common/commonfuntion.js"></script>
    
    <!-- css -->
    <!-- <link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css" /> -->
    <link rel="stylesheet" type="text/css" href="../../css/uploadImg.css" />
    <link rel="stylesheet" type="text/css" href="../../css/orderdetail.css" />
    <link rel="stylesheet" type="text/css" href="../../layui/css/layui.css">
    <link rel="stylesheet" type="text/css" href="../../css/mobiscroll.custom.min.css" />
    <link rel="stylesheet" href="https://at.alicdn.com/t/font_1805932_ysrcp4y0uy9.css">

    <style>
        html,body{
            height:100%;
        }

        .main{
            width:100%;
        }

        .main .upload-content h3{
            font-size: 0.28rem;
            color: #7F94B2;
            letter-spacing: 0;
            font-weight: bold;
        }

        .main .upload-content .content-img .file{
            width:60px;
            height:60px;
            line-height:60px;
        }
        .main .upload-content .content-img .file input{
            width:60px;
            height:60px;
        }
        .main .upload-content .content-img .content-img-list .content-img-list-item{
            width:60px;
            height:60px;
            line-height:60px;
        }
        .main .upload-content .content-img .content-img-list .content-img-list-item >img{
            width:100%;
            height:100%;
            display:block;
            overflow:hidden;
        }

        .main .upload-content .content-img-list-item div{
            line-height:60px;
        }

        .jjcd{
            margin-top:20px;
            width:100%;
        }

        .jjcd select{
            width:70%;
            border: 1px solid rgba(1,103,255,0.3);
            border-radius: 31px;
            background:transparent;
            font-family: SourceHanSansCN-Regular;
            font-size: 14px;
            color: #0167FF;
            letter-spacing: 1.75px;
            text-indent:10px;
            height:30px;
        }

        
    </style>
</head>

<body>
    <div id="container" class="orderdetail">
        <div class="orderdetail_01">
            <!--主屏内容-->
            <div class="orderdetail_screen">
                <div class="m_title">
                    <a href="JavaScript:history.go(-1);" class="back">
                        <img src="../../images/back.svg" alt="">
                    </a>
                    <span class="tit" id="showname">工单管理</span>
                </div>

                <ul class="gj_con" style="margin-top:75px;">
                    <li>
                        <span class="lileft">工单名称</span><span class="liright">
                            <input type="text" placeholder="请输入工单名称" id="gdname" />
                        </span>
                    </li>
                    <li>
                        <span class="lileft">填报人</span><span class="liright" id="tbr"></span>
                    </li>
                    <li>
                        <span class="lileft">执行人</span><span class="liright" id="zxr"></span>
                    </li>
                    <li>
                        <span class="lileft">联系方式</span><span class="liright">
                            <input type="tel" placeholder="请输入联系方式" id="tel" />
                        </span>
                    </li>
                    <li>
                        <span class="lileft">创建时间</span><span class="liright" id="createtime"></span>
                    </li>
                </ul>
                

                <div class="cljg hdnr_con" style="margin-top:20px;">
                    <div class="cljg_tit tit" style="font-weight: bold;">问题描述</div>
                    <textarea name="" id="questioncon" placeholder="请输入处理结果"></textarea>
                </div>

                <div class="jjcd">
                    <select id="selectxm" value="">
                        <option value="0" selected>请选择紧急程度</option>
                        <option value="1">非常紧急</option>
                        <option value="2">紧急</option>
                        <option value="3">不紧急</option>
                    </select>
                </div>



                <div class="main" id="sctp" style="margin-top:20px;">
                    <div class="upload-content">
                        <h3>上传图片</h3>
                        <div class="content-img">
                            <ul class="content-img-list" id="img_wrap"></ul>
                            <div class="file">
                                <i class="gcl gcladd"></i>
                                <input type="file" name="file" accept="image/*" id="upload" multiple="multiple" />
                            </div>
                        </div>
                        <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
                            <div class="modal-dialog modal-lg" role="document">
                                <div class="modal-content">
            
                                </div>
                            </div>
                        </div>
                    </div>
                </div>


                <!-- 上传文件 -->
                <div class="hdnr_tit title" style="font-size: 0.28rem;">上传附件</div>
                <div class="layui-upload" style="margin-top:0.4rem;">
                    <div class="layui-upload-list">
                        <table class="layui-table">
                            <thead>
                                <tr>
                                    <th>文件名</th>
                                    <th>大小</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="demoList"></tbody>
                        </table>
                    </div>

                    <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
                    <button type="button" class="layui-btn" id="testListAction" style="font-size:0.24rem;">开始上传</button>

                </div>


                <div class="wrap_btn">
                    <div class="sub_btn" style="margin-top:1rem;" id="sub_btn">提 交</div>
                </div>

            </div>
        </div>
    </div>


    <script>
        (function (win, doc) {
            var docEl = doc.documentElement || document.body; //获取HTML标签

            var container = doc.getElementById("container"); //container元素
            //判断是移动端设备还是PC,移动 就采用'orientationchange',横竖屏事件，PC端就采用onresize，窗口改变时间
            var resize =
                "onorientationchange" in win ? "orientationchange" : "resize";

            function rem() {
                docEl.style.fontSize = 100 * (container.clientWidth / 750) + "px";
            }

            //监听'DOMContent事件:DOM加载完成执行,如果DOMContent事件，那么执行rem函数
            doc.addEventListener("DOMContentLoaded", rem, false);

            //win下监听resize事件,如果resize事件，那么执行rem函数
            win.addEventListener(resize, rem, false);
        })(window, document);
    </script>
    <!-- js -->
    <script type="text/javascript" src="../../js/jquery.min.js"></script>
    <script type="text/javascript" src="../../js/mobiscroll.custom.min.js"></script>
    <script type="text/javascript" src="../../layui/layui.js"></script>
    <script>
        $(document).ready(function () {

            var projectid = GetQueryString('projectid');
            var projectNameCN = GetQueryString('projectname');
            $("#showname").html();
            $("#showname").html(projectNameCN);

            // 填报人
            $("#tbr").html( window.localStorage.getItem('name') );

            // 获取执行人
            var executorid,executorname;
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "http://112.74.169.99:21021/api/services/app/DevOpsService/GetSaleOrderUserInfo",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Accept",
                        "application/json, text/javascript, */*; q=0.01"
                    );
                    xhr.setRequestHeader("Authorization", accessToken);
                    xhr.setRequestHeader('.AspNetCore.Culture',
                        'zh-Hans');
                },
                success: function (res) {
                    console.log(res);
                    executorid = res.result.userID;
                    executorname = res.result.userName;
                    if(res.success){
                        $("#zxr").html( ' ' );
                        $("#zxr").html( res.result.userName );
                    }
                },
                error: function (err) {
                    console.log("请求失败");
                }
            });

            // 图片上传
            var imgFile = []; //文件流
            var imgSrc = []; //图片路径
            var imgBlob = []; //图片Blob
            // 鼠标经过显示删除按钮
            $('.content-img-list').on('mouseover', '.content-img-list-item', function() {
                $(this).children('div').removeClass('hide');
            });
            // 鼠标离开隐藏删除按钮
            $('.content-img-list').on('mouseleave', '.content-img-list-item', function() {
                $(this).children('div').addClass('hide');
            });

            // 上传图片功能
            $('#upload').on('change', function(e) {
                var fileList = this.files;

                var imgBox = '.content-img-list';
                async function upload(file){
                    for(var j = 0; j < file.length; j++){
                        const img = await readImg( file[j] );
                        const blob = await compressImg( img, file[j].type, 1000, 600 );
                        
                        if (blob.size > 1024 * 1024 * 1) { //1MB
                            return alert("上传图片不能超过1MB");
                        };

                        if (blob.type != 'image/png' && blob.type != 'image/jpeg' && blob.type != 'image/gif') {
                            return alert("图片上传格式不正确");
                        }

                        imgBlob.push(blob);
                        imgFile.push(file[j]); //文件流

                        var imgSrcI = getObjectURL(file[j]);
                        imgSrc.push(imgSrcI); //图片路径
                        
                    }
                    addNewContent(imgBox);
                }

                upload( fileList ).catch(e => console.log(e));

                
            });

            // 单个图片删除
            $(".content-img-list").on("click", '.content-img-list-item a .gcllajitong', function() {
                var index = $(this).parent().parent().parent().index();
                imgSrc.splice(index, 1);
                imgFile.splice(index, 1);
                var boxId = ".content-img-list";
                addNewContent(boxId);
            });


            //图片展示
            function addNewContent(obj) {
                $(obj).html("");
                for (var a = 0; a < imgSrc.length; a++) {
                    var oldBox = $(obj).html();
                    $(obj).html(oldBox + '<li class="content-img-list-item"><img src="' + imgSrc[a] + '" alt="">' +
                        '<div class="hide"><a index="' + a + '" class="delete-btn"><i class="gcl gcllajitong"></i></a>');
                }
            }

            //建立可存取到file的url
            function getObjectURL(file) {
                var url = null;
                if (window.createObjectURL != undefined) { // basic
                    url = window.createObjectURL(file);
                } else if (window.URL != undefined) { // mozilla(firefox)
                    url = window.URL.createObjectURL(file);
                } else if (window.webkitURL != undefined) { // webkit or chrome
                    url = window.webkitURL.createObjectURL(file);
                }
                return url;
            }


            // 压缩前将file转换成img对象
            function readImg(file) {
                return new Promise((resolve, reject) => {
                    const img = new Image()
                    const reader = new FileReader()
                    reader.onload = function(e) {
                        img.src = e.target.result
                    }
                    reader.onerror = function(e) {
                        reject(e)
                    }
                    reader.readAsDataURL(file)
                    img.onload = function() {
                        resolve(img)
                    }
                })
            }

            function compressImg(img, type, mx, mh) {
                return new Promise((resolve, reject) => {
                    const canvas = document.createElement('canvas')
                    const context = canvas.getContext('2d')
                    const { width: originWidth, height: originHeight } = img
                    // 最大尺寸限制
                    const maxWidth = mx
                    const maxHeight = mh
                    // 目标尺寸
                    let targetWidth = originWidth
                    let targetHeight = originHeight
                    if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > 1) {
                        // 宽图片
                        targetWidth = maxWidth
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                    } else {
                        // 高图片
                        targetHeight = maxHeight
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                    }
                    }
                    canvas.width = targetWidth
                    canvas.height = targetHeight
                    context.clearRect(0, 0, targetWidth, targetHeight)
                    // 图片绘制
                    context.drawImage(img, 0, 0, targetWidth, targetHeight)
                    canvas.toBlob(function(blob) {
                        resolve(blob)
                    }, type || 'image/png')
                })
            }

            var uploadfile = [];
            // 上传附件
            layui.use('upload', function(){
                var $ = layui.jquery
                ,upload = layui.upload;

                var demoListView = $('#demoList')
                ,uploadListIns = upload.render({
                    elem: '#testList'
                    ,url: 'http://112.74.169.99:21021/api/FileUpload/GatherImageUploadPost' //改成您自己的上传接口
                    ,accept: 'file'
                    ,multiple: true
                    ,auto: false
                    ,bindAction: '#testListAction'
                    ,choose: function(obj){
                        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                        //读取本地文件
                        obj.preview(function(index, file, result){
                        var tr = $(['<tr id="upload-'+ index +'">'
                            ,'<td>'+ file.name +'</td>'
                            ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                            ,'<td>等待上传</td>'
                            ,'<td>'
                                ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                                ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                                ,'</td>'
                            ,'</tr>'].join(''));

                        //单个重传
                        tr.find('.demo-reload').on('click', function(){
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function(){
                            delete files[index]; //删除对应的文件
                            tr.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });

                        demoListView.append(tr);
                        });
                    }
                    ,done: function(res, index, upload){
                        if(res.result.fileurl){
                            var filename = [];
                            for(var x in res.result){
                                filename.push(res.result[x]);
                            }
                            uploadfile.push(filename);

                            var tr = demoListView.find('tr#upload-'+ index)
                            ,tds = tr.children();
                            tds.eq(2).html('<span style="color: #5FB878;" judge="done">上传成功</span>');
                            tds.eq(3).html(''); //清空操作
                        }
                        // this.error(index, upload);
                    }
                    ,error: function(index, upload){
                        var tr = demoListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                        tds.eq(2).html('<span style="color: #FF5722;" judge="failure">上传失败</span>');
                        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                    }
                });
            });



            // 获取当前时间
            $("#createtime").html( getDate() );
            
            function getDate(){
                var myDate = new Date();
                //获取当前年
                var year = myDate.getFullYear();
                //获取当前月
                var month = myDate.getMonth() + 1;
                //获取当前日
                var date = myDate.getDate();
                var h = myDate.getHours(); //获取当前小时数(0-23)
                var m = myDate.getMinutes(); //获取当前分钟数(0-59)
                var s = myDate.getSeconds();
                //获取当前时间
                var now = year + '-' + conver(month) + "-" + conver(date) + " " + conver(h) + ':' + conver(m) + ":" + conver(s);
                return now;
            }

            //日期时间处理
            function conver(s) {
                return s < 10 ? '0' + s : s;
            }

            // 提交按钮
            var uploadimg = [];
            $("#sub_btn").click(function(){
                console.log(imgFile);
                
                console.log(uploadfile);

                
                var ordername,stepnum,orderstate,ordercontant,problemDescription,degreeOfUrgency,problemPhoto,problemFile,createrid,creatername,creattime;
                ordername = $("#gdname").val();
                console.log(ordername);
                if( !ordername ){
                    layer.msg('请输入工单名称', {
                        icon: 2,
                        time: 1000 //1秒关闭（如果不配置，默认是3秒）
                    })
                }



                const main = async () => {
                    if(imgFile.length > 0){
                        for(let i = 0; i < imgFile.length; i++){
                            var formFile = '';
                            formFile = new FormData();
                            formFile.append('file', imgBlob[i], imgFile[i].name);

                            await $.ajax({
                                url: 'http://112.74.169.99:21021/api/FileUpload/GatherImageUploadPost',
                                type: 'post',
                                data: formFile,
                                async: true,
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function(res){
                                    console.log('图片上传成功');
                                    uploadimg.push(res.result.fileurl);
                                },
                                error: function(res){
                                    console.log(res);
                                }
                            });
                        }
                    }
                    ordercontant = {
                        uploadimg:uploadimg,
                        uploadfile:uploadfile
                    }
                    orderContant = {
                        contant00 : ordercontant
                    }
                    orderContant = JSON.stringify(orderContant);
                    
                    var subdata = {
                        projectID: projectid, //项目id
                        ordername: $("#gdname").val(), //工单名称
                        creattime: $("#createtime").html(), //创建时间
                        executorid: executorid, //当前执行人id （更新）
                        executorname: executorname, //当前执行人（更新）
                        telePhone: $("#tel").val(),
                        problemDescription: $("#questioncon").val(), //问题描述
                        stepnum: 0, //执行次数（更新 每次提交加1）
                        orderstate: 0, //工单状态 0-待处理 1-提交工单完结 2-已完成 
                        ordercontant: orderContant,  //工单内容（更新）      json
                        degreeOfUrgency: $("#selectxm").val(), //紧急程度
                        createrid: window.localStorage.getItem('id'), //填报人id
                        creatername: window.localStorage.getItem('name'), //填报人姓名
                    }
                    console.log(subdata);
                    subdata = JSON.stringify(subdata);
                    // return;

                    $.ajax({
                        url: "http://112.74.169.99:21021/api/services/app/DevOpsService/CreatAfterSaleOrder",
                        data: subdata,
                        type: "post",
                        dataType: "json",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("Content-Type", "application/json");
                            xhr.setRequestHeader(
                                "Accept",
                                "application/json, text/plain, */*"
                            );
                        },
                        success: function (res) {
                            console.log(res);
                            window.location.href = "../project_aftersale.html?projectid=" + projectid + "&projectname=" +projectNameCN;
                        
                        },
                        error: function (err) {
                            console.log("请求失败");
                        }
                    });

                };
                main();
            

            });
            



        });
    </script>

</body>

</html>